//RepelBlock
importPackage(com.blocks.blocks);
importPackage(com.blocks);
importPackage(com.blocks.model);
importPackage(com.jme3.math);
importPackage(java.lang);
importPackage(com.blocks.script);
importPackage(com.jme3.math);
importPackage(com.jme3.collision);
importPackage(com.jme3.scene.debug);
importPackage(com.jme3.scene);
importPackage(com.jme3.material);




var block = new Object(); 
var counter = 0;
var color = 0 ; //0-5
var direction = 0;
var rayHit = false;
var mark;
;


block.setup = function(name) {
 	thisBlock.setName("Repel");
 	thisBlock.setTextureRow(1.0);
	thisBlock.setTextureColumn(5.0);
 	thisBlock.resetTexture();
	thisBlock.setCustomFrequency(true);
        block.initMark();
	
  } 
block.loop = function(name, tpf) { 
	if( thisBlock.isPowered()){
		results = new CollisionResults();
		direction = thisBlock.getWorldRotation().getRotationColumn(2);
		ray = new Ray(thisBlock.getWorldTranslation(), direction);
			ScriptBlocksApplication.getInstance().getRootNode()
					.collideWith(ray, results);
		var found = false;
		var forceVector = Vector3f.ZERO;
		var distance = 0
		if (results.size() > 0) {
			itr = results.iterator(); 
			while(itr.hasNext()) {
   				closest = itr.next(); 
				if(closest.getGeometry() != null && closest.getDistance()>2 && closest.getDistance()<50){
					hitNode = closest.getGeometry().getParent();
					if ( ScriptUtils.isBlock(hitNode)) {	
						mark.setLocalTranslation(thisBlock.getWorldTranslation());				
		   				mark.setLocalRotation(thisBlock.getWorldRotation());
						masterBlock = ScriptBlocksApplication.getInstance().getMasterBlock(thisBlock.getMasterId());
																	
						var newVector = thisBlock.getWorldTranslation().subtract(hitNode.getWorldTranslation()).normalize();
						distance = closest.getDistance();
						var frequency = thisBlock.getFrequency(thisBlock.getBlockSides())==0? 0 : thisBlock.getFrequency(thisBlock.getBlockSides())/distance;
						forceVector = newVector.mult(frequency*tpf);						
						masterBlock.setLocalTranslation(masterBlock.getLocalTranslation().add(forceVector));
						ScriptBlocksApplication.getInstance().getRootNode().attachChild(mark);
						thisBlock.setAllFrequency(FastMath.abs(distance));	
						found = true;
						break;			
					}
				}							
			}			
		}if(!found) {			
			ScriptBlocksApplication.getInstance().getRootNode().detachChild(mark);
			thisBlock.setAllFrequency(0);	
		}
		 
	}	
 }


block.scriptExport = function() {
	return ("");
} 

 block.initMark = function() {
       var arrow = new Arrow(Vector3f.UNIT_Z.mult(50));
        arrow.setLineWidth(3);

        mark = new Geometry("BOOM!", arrow);

        mark_mat = new Material(ScriptBlocksApplication.getInstance()
				.getAssetManager(), "Common/MatDefs/Misc/SolidColor.j3md");
        mark_mat.setColor("Color", ColorRGBA.Red);
        mark.setMaterial(mark_mat);
    }



